<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">






  
  
    
      
    
    
      
    
  <script src="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script>
  <link href="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">



<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("http://xxxxxxx.xxx"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>





<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="zrNUWIf25v2J4dC1wliso_DUXEwYoECv4j3h9CE34xM">








  <meta name="baidu-site-verification" content="nuHze5uXZ7">







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">




<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.2',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="“用了一段时间HEXO搭建个人的博客，但每次发布文章，都需要打开电脑hexo g编译之后，再提交到服务器上，确实挺麻烦的，我是个懒人，这个不能忍，快捷发布日志这个问题需要解决一下了！Travis CI搞起来！”">
<meta name="keywords" content="Hexo,github,travis,博客,自动部署">
<meta property="og:type" content="article">
<meta property="og:title" content="利用Travis实现Hexo博客的github and server自动部署">
<meta property="og:url" content="https://blog.codenote.pro/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html">
<meta property="og:site_name" content="九阳的笔记本">
<meta property="og:description" content="“用了一段时间HEXO搭建个人的博客，但每次发布文章，都需要打开电脑hexo g编译之后，再提交到服务器上，确实挺麻烦的，我是个懒人，这个不能忍，快捷发布日志这个问题需要解决一下了！Travis CI搞起来！”">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-10-29T14:22:48.759Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="利用Travis实现Hexo博客的github and server自动部署">
<meta name="twitter:description" content="“用了一段时间HEXO搭建个人的博客，但每次发布文章，都需要打开电脑hexo g编译之后，再提交到服务器上，确实挺麻烦的，我是个懒人，这个不能忍，快捷发布日志这个问题需要解决一下了！Travis CI搞起来！”">



  <link rel="alternate" href="/atom.xml" title="九阳的笔记本" type="application/atom+xml">




  <link rel="canonical" href="https://blog.codenote.pro/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>利用Travis实现Hexo博客的github and server自动部署 | 九阳的笔记本</title>
  




<script async src="https://www.googletagmanager.com/gtag/js?id=UA-126970002-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-126970002-1');
</script>



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?07b2f6778635ec267ee2b4753e118da9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
     
    
    
    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">九阳的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-hexo">
    <a href="/categories/Hexo" rel="section">
      <i class="menu-item-icon fa fa-fw fa-header"></i> <br>Hexo</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-linux">
    <a href="/categories/Linux" rel="section">
      <i class="menu-item-icon fa fa-fw fa-linux"></i> <br>Linux</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-docker">
    <a href="/categories/docker" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>docker</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-learn">
    <a href="/categories/learn" rel="section">
      <i class="menu-item-icon fa fa-fw fa-leanpub"></i> <br>学习</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br>阅读排行</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.codenote.pro/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yszar">
      <meta itemprop="description" content="学无止境！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="九阳的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">利用Travis实现Hexo博客的github and server自动部署
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-02 15:49:47" itemprop="dateCreated datePublished" datetime="2018-10-02T15:49:47+08:00">2018-10-02</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-10-29 22:22:48" itemprop="dateModified" datetime="2018-10-29T22:22:48+08:00">2018-10-29</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Hexo/" itemprop="url" rel="index"><span itemprop="name">Hexo</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html" class="leancloud_visitors" data-flag-title="利用Travis实现Hexo博客的github and server自动部署">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          
              <div class="post-description">“用了一段时间HEXO搭建个人的博客，但每次发布文章，都需要打开电脑hexo g编译之后，再提交到服务器上，确实挺麻烦的，我是个懒人，这个不能忍，快捷发布日志这个问题需要解决一下了！Travis CI搞起来！”</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p class="description">用了一段时间HEXO搭建个人的博客，但每次发布文章，都需要打开电脑hexo g编译之后，再提交到服务器上，确实挺麻烦的，我是个懒人，这个不能忍，快捷发布日志这个问题需要解决一下了！Travis CI搞起来！</p>

<a id="more"></a>
<h1 id="HEXO的开发分支与生产分支"><a href="#HEXO的开发分支与生产分支" class="headerlink" title="HEXO的开发分支与生产分支"></a>HEXO的开发分支与生产分支</h1><p>仓库分成2个分支，主开发开支dev，以及生产环境的gh-pages分支。<br>查看博客可以通过访问<a href="https://yszar.github.io" target="_blank" rel="noopener">我的github pages</a>。</p>
<h2 id="开发分支-dev"><a href="#开发分支-dev" class="headerlink" title="开发分支 dev"></a>开发分支 dev</h2><p>在我的博客里，开发分支是dev，目录结构就是一开始hexo init后的结构。</p>
<ul>
<li><code>caffolds</code> // 页面的模板，包括草稿（draft.md）、页面（page.md）、文章（post.md）以及其他自定义模板</li>
<li><code>source</code> // 放页面和文章markdown文档</li>
<li><code>themes</code> // 博客主题</li>
<li><code>_config.yml</code> // 配置文件</li>
<li><code>package.json</code></li>
<li><code>.travis.yml</code> // 持续集成服务travis的文件</li>
</ul>
<p>本地开发流程一般是这样。</p>
<p>// hexo server, 启动本地服务器，预览我的文章<br>hexo s </p>
<p>// hexo generate，编译文章，把 <code>source</code> 里面的页面和文章编译成 <code>public</code> 里面的html文件<br>hexo g</p>
<p>// hexo deploy，如果 _config.yml 有配置deploy的内容，执行该命令是会执行相应的部署逻辑<br>hexo d</p>
<p>HEXO的详细科普和指令在这里就不写了哈，官方文档里都有 <a href="https://link.zhihu.com/?target=https%3A//hexo.io/docs/" rel="external nofollow noopener noreferrer" target="_blank">&gt;&gt; 传送门</a>。</p>
<h2 id="生产分支-gh-pages"><a href="#生产分支-gh-pages" class="headerlink" title="生产分支 gh-pages"></a>生产分支 gh-pages</h2><p>在dev分支里，执行了hexo g编译之后，编译后的静态文件会存在public文件夹里，而我们就把里面的内容挪到最终的生产环境分支gh-pages里，也就是最终我们看到的静态博客。</p>
<p>当我们在github里把github-pages服务打开，并渲染gh-pages分支，我们就能访问自己的博客了（<a href="https://yszar.github.io）。" rel="external nofollow noopener noreferrer" target="_blank">https://yszar.github.io）。</a></p>
<h1 id="Travis-CI"><a href="#Travis-CI" class="headerlink" title="Travis CI"></a>Travis CI</h1><p>在大致了解HEXO的开发流程之后，我们可以开始考虑，如果要实现快捷发布，是要做什么？</p>
<p><code>User Story</code>：希望可以在github上写一篇文章，提交之后，可以直接在我的线上博客看到。</p>
<p>在这里，我们用到了提供持续集成（CI, Continuous Integration）服务的Travis CI，但其实用到的不是它提供的CI服务，而更多的是通过监听分支提交的动态，在集成成功后去执行我们自定义的部署逻辑。</p>
<p>持续集成是一种软件开发实践，即团队开发成员经常集成他们的工作，通过每个成员每天至少集成一次，也就意味着每天可能会发生多次集成。每次集成都通过自动化的构建（包括编译，发布，自动化测试）来验证，从而尽早地发现集成错误。</p>
<p>噢，还有些事前准备：</p>
<ul>
<li>先在dev分支里，创建.travis.yml</li>
<li>在Travis CLI平台上打开这个分支的CI开关</li>
</ul>
<h2 id="1-编译并同步到gh-pages"><a href="#1-编译并同步到gh-pages" class="headerlink" title="1. 编译并同步到gh-pages"></a><strong>1. 编译并同步到gh-pages</strong></h2><p>那直接上我的CI配置代码吧。</p>
<figure class="highlight yml"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div></pre></div><div class="code"><pre><div class="line"><span class="attr">language:</span> <span class="string">node_js</span></div><div class="line"><span class="attr"> node_js:</span> <span class="string">stable</span></div><div class="line"></div><div class="line"> <span class="comment"># Travis-CI Caching</span></div><div class="line"><span class="attr"> cache:</span></div><div class="line"><span class="attr">   directories:</span></div><div class="line"><span class="bullet">     -</span> <span class="string">node_modules</span></div><div class="line"></div><div class="line"></div><div class="line"> <span class="comment"># S: Build Lifecycle</span></div><div class="line"><span class="bullet">   -</span> <span class="string">node_modules</span></div><div class="line"><span class="attr"> install:</span></div><div class="line"><span class="bullet">   -</span> <span class="string">npm</span> <span class="string">install</span></div><div class="line"></div><div class="line"><span class="attr"> before_script:</span></div><div class="line">  <span class="comment"># - npm install -g gulp</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="bullet"> -</span> <span class="string">npm</span> <span class="string">install</span></div><div class="line"><span class="attr"> before_script:</span> </div><div class="line"><span class="attr"> script:</span></div><div class="line"><span class="bullet">   -</span> <span class="string">hexo</span> <span class="string">g</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="attr"> after_script:</span></div><div class="line"><span class="bullet">   -</span> <span class="string">cd</span> <span class="string">./public</span></div><div class="line"><span class="bullet">   -</span> <span class="string">git</span> <span class="string">init</span></div><div class="line"><span class="bullet">   -</span> <span class="string">git</span> <span class="string">config</span> <span class="string">user.name</span> <span class="string">"yszar"</span></div><div class="line"><span class="bullet">   -</span> <span class="string">git</span> <span class="string">config</span> <span class="string">user.email</span> <span class="string">"yszar@vip.qq.com"</span></div><div class="line"><span class="bullet">   -</span> <span class="string">git</span> <span class="string">add</span> <span class="string">.</span></div><div class="line"><span class="bullet">   -</span> <span class="string">git</span> <span class="string">commit</span> <span class="bullet">-m</span> <span class="string">"Update docs"</span></div><div class="line"><span class="bullet">   -</span> <span class="string">git</span> <span class="string">push</span> <span class="bullet">--force</span> <span class="bullet">--quiet</span> <span class="string">"https://$&#123;GH_TOKEN&#125;@$&#123;GH_REF&#125;"</span> <span class="attr">master:master</span></div><div class="line"> <span class="comment"># E: Build LifeCycle</span></div><div class="line"></div><div class="line"><span class="bullet"> -</span> <span class="string">hexo</span> <span class="string">g</span></div><div class="line"><span class="attr"> after_success:</span></div><div class="line"><span class="bullet"> -</span> <span class="string">cd</span> <span class="string">./public</span></div><div class="line"><span class="bullet"> -</span> <span class="string">git</span> <span class="string">init</span></div><div class="line"><span class="bullet"> -</span> <span class="string">git</span> <span class="string">config</span> <span class="string">user.name</span> <span class="string">"yszar"</span></div><div class="line"><span class="bullet"> -</span> <span class="string">git</span> <span class="string">config</span> <span class="string">user.email</span> <span class="string">"yszar@vip.qq.com"</span></div><div class="line"><span class="bullet"> -</span> <span class="string">git</span> <span class="string">add</span> <span class="string">.</span></div><div class="line"><span class="bullet"> -</span> <span class="string">git</span> <span class="string">commit</span> <span class="bullet">-m</span> <span class="string">"Update docs"</span></div><div class="line"><span class="bullet"> -</span> <span class="string">git</span> <span class="string">push</span> <span class="bullet">--force</span> <span class="bullet">--quiet</span> <span class="string">"https://$&#123;GH_TOKEN&#125;@$&#123;GH_REF&#125;"</span> <span class="attr">master:master</span></div><div class="line"> <span class="comment"># other actions</span></div><div class="line"><span class="bullet"> -</span> <span class="string">scp</span> <span class="bullet">-o</span> <span class="string">stricthostkeychecking=no</span> <span class="bullet">-r</span> <span class="string">./*</span> <span class="string">root@39.107.81.83:/www/wwwroot/hexo-blog/</span></div><div class="line"><span class="attr"> branches:</span></div><div class="line"><span class="attr">   only:</span></div><div class="line"><span class="bullet">     -</span> <span class="string">hexocode</span></div><div class="line"><span class="bullet">   -</span> <span class="string">hexocode</span></div><div class="line"><span class="attr"> env:</span></div><div class="line"><span class="attr">  global:</span></div><div class="line"><span class="attr">    - GH_REF:</span> <span class="string">github.com/yszar/yszar.github.io</span></div><div class="line"><span class="attr">   global:</span></div><div class="line"><span class="attr">   - GH_REF:</span> <span class="string">github.com/yszar/yszar.github.io</span></div><div class="line"><span class="attr"> before_install:</span></div><div class="line"><span class="bullet"> -</span> <span class="string">openssl</span> <span class="string">aes-256-cbc</span> <span class="bullet">-K</span> <span class="string">$encrypted_0d4a7a01eced_key</span> <span class="bullet">-iv</span> <span class="string">$encrypted_0d4a7a01eced_iv</span></div><div class="line"><span class="bullet">   -</span><span class="string">in</span> <span class="string">codenote.pem.enc</span> <span class="bullet">-out</span> <span class="string">~/.ssh/codenote.pem</span> <span class="bullet">-d</span></div><div class="line"><span class="bullet"> -</span> <span class="string">chmod</span> <span class="number">600</span> <span class="string">~/.ssh/codenote.pem</span></div><div class="line"><span class="bullet"> -</span> <span class="string">echo</span> <span class="bullet">-e</span> <span class="string">"Host 你的服务器IP\n\tStrictHostKeyChecking no\n"</span> <span class="string">&gt;&gt;</span> <span class="string">~/.ssh/config</span></div></pre></div></div></figure>
<p>相信代码和注释写得很清楚了，有个地方需要进一步解释的，github提交那part，涉及github access token的生成和加密。</p>
<ol>
<li>生成github的<a href="https://link.zhihu.com/?target=https%3A//github.com/settings/tokens" rel="external nofollow noopener noreferrer" target="_blank">Personal Access Tokens</a>（打开分支提交的权限）</li>
<li>安装Travis CLI <code>gem install travis</code>（如果登录遇到环境问题，可以看看下面参考文章里面的解决方案）</li>
<li>进入到本地<code>dev</code>目录下（带有<code>.travis.yml</code>），执行<code>travis login</code>登录，再执行<code>travis encrypt &#39;GH_TOKEN=${your_github_personal_access_token}&#39; --add</code>加密你的personal access token（也就是后来<code>.travis.yml</code>的<code>env.global.secure</code>的值）</li>
</ol>
<p>把<code>.travis.yml</code>提交之后，看看Travis CLI上，开始持续集成了哈。</p>
<p>大功告成，集成之后，在github pages的页面上也能看到文章的更新。</p>
<h2 id="2-CI到我的服务器"><a href="#2-CI到我的服务器" class="headerlink" title="2. CI到我的服务器"></a><strong>2. CI到我的服务器</strong></h2><hr>
<p>我的服务器是阿里云的，一开始服务器初始化的过程，大家可以参考各个server商提供的setup文档哈，总的来说，在本地有个服务器信任的<code>id_rsa</code>的ssh文件，我们是可以通过<code>ssh user@ip_address</code>登录到服务器的。<br><figure class="highlight yml"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></div><div class="code"><pre><div class="line"><span class="comment"># 这个命令会自动把 id_rsa 加密传送到 .git 指定的仓库对应的 travis 中去（在我本地这个文件叫qq_rsa，不是默认的id_rsa）</span></div><div class="line"><span class="string">travis</span> <span class="string">encrypt-file</span> <span class="string">~/.ssh/id_rsa</span> <span class="bullet">--add</span></div></pre></div></div></figure></p>
<p>执行这个命令后，<code>.travis.yml</code>多了一行代码：（注意把其中的转义符<code>\</code>干掉哈），也会在分支目录下生成一个<code>id_rsa.enc</code>的加密文件，记得把这个文件也提交上去哟。</p>
<figure class="highlight yml"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></div><div class="code"><pre><div class="line"><span class="attr">before_install:</span></div><div class="line"><span class="bullet">-</span> <span class="string">openssl</span> <span class="string">aes-256-cbc</span> <span class="bullet">-K</span> <span class="string">$encrypted_3cf6c1fd150f_key</span> <span class="bullet">-iv</span> <span class="string">$encrypted_3cf6c1fd150f_iv</span></div><div class="line"><span class="bullet">  -</span><span class="string">in</span> <span class="string">qq_rsa.enc</span> <span class="bullet">-out</span> <span class="string">~/.ssh/id_rsa</span> <span class="bullet">-d</span></div></pre></div></div></figure>
<p>然后为了保证在Travis里面能正常执行，我们处理下运行环境的rsa文件权限和输出提示信息，before_install如下。</p>
<figure class="highlight yml"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></div><div class="code"><pre><div class="line"><span class="attr">before_install:</span></div><div class="line"><span class="bullet">-</span> <span class="string">openssl</span> <span class="string">aes-256-cbc</span> <span class="bullet">-K</span> <span class="string">$encrypted_3cf6c1fd150f_key</span> <span class="bullet">-iv</span> <span class="string">$encrypted_3cf6c1fd150f_iv</span></div><div class="line"><span class="bullet">  -</span><span class="string">in</span> <span class="string">qq_rsa.enc</span> <span class="bullet">-out</span> <span class="string">~/.ssh/id_rsa</span> <span class="bullet">-d</span></div><div class="line"><span class="bullet">-</span> <span class="string">chmod</span> <span class="number">600</span> <span class="string">~/.ssh/id_rsa</span></div><div class="line"><span class="bullet">-</span> <span class="string">echo</span> <span class="bullet">-e</span> <span class="string">"Host 主机IP地址\n\tStrictHostKeyChecking no\n"</span> <span class="string">&gt;&gt;</span> <span class="string">~/.ssh/config</span></div></pre></div></div></figure>
<p>最后，在<code>after_success</code>里添加<strong>拷贝目标文件到服务器目标目录</strong>的操作，就大功告成了！</p>
<figure class="highlight yml"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></div><div class="code"><pre><div class="line"><span class="string">after_success</span></div><div class="line"><span class="comment"># other actions</span></div><div class="line"><span class="bullet">-</span> <span class="string">scp</span> <span class="bullet">-o</span> <span class="string">stricthostkeychecking=no</span> <span class="bullet">-r</span> <span class="string">./*</span> <span class="string">root@39.107.81.83:/home/yszar/public/blog/</span></div></pre></div></div></figure>

      
    </div>

    
      


    

    
    
    
    
    <div>
        
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        
    </div>
    
    <div>
          
            
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html">利用Travis实现Hexo博客的github and server自动部署</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 yszar 的个人博客">yszar</a></p>
  <p><span>发布时间:</span>2018年10月02日 - 15:10</p>
  <p><span>最后更新:</span>2018年10月29日 - 22:10</p>
  <p><span>原始链接:</span><a href="/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html" title="利用Travis实现Hexo博客的github and server自动部署">https://blog.codenote.pro/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fas fa-copy" data-clipboard-text="https://blog.codenote.pro/realize-the-automatic-deployment-of-github-and-server-on-hexo-blog-with-travis.html" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="external nofollow noopener noreferrer" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>


          
    </div>

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="yszar wechat" style="width: 200px; max-width: 100%;">
    <div>欢迎您扫一扫上面的微信公众号，订阅我的博客！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/uploads/wxfk.png" alt="yszar 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/uploads/zfbfk.png" alt="yszar 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Hexo/" rel="tag"><i class="fa fa-tag"></i> Hexo</a>
          
            <a href="/tags/github/" rel="tag"><i class="fa fa-tag"></i> github</a>
          
            <a href="/tags/travis/" rel="tag"><i class="fa fa-tag"></i> travis</a>
          
            <a href="/tags/博客/" rel="tag"><i class="fa fa-tag"></i> 博客</a>
          
            <a href="/tags/自动部署/" rel="tag"><i class="fa fa-tag"></i> 自动部署</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        
          <div class="wp_rating">
          <div style="color: rgba(0, 0, 0, 0.75); font-size:13px; letter-spacing:3px">(&gt;看完记得五星好评哦亲&lt;)</div>
            <div id="wpac-rating"></div>
          </div>
        

        

        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
            
              
              <a href="/this-blog-hexo-next-githubpages-optimization.html" rel="prev" title="本博客Hexo NexT GitHubPages优化">
                
                <i class="fa fa-chevron-left"></i> 本博客Hexo NexT GitHubPages优化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
            
              
              <a href="/host-the-hexo-blog-at-githuboschinacoding.html" rel="next" title="将Hexo博客同时托管在Github-oschina-coding">
                
                将Hexo博客同时托管在Github-oschina-coding <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
       <div id="gitalk-container"></div>
       <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">yszar</p>
              <p class="site-description motion-element" itemprop="description">学无止境！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">21</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yszar" target="_blank" title="GitHub" rel="external nofollow noopener noreferrer"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yszar@vip.qq.com" target="_blank" title="E-Mail" rel="external nofollow noopener noreferrer"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow noopener noreferrer">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          

          
            
          
          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#HEXO的开发分支与生产分支"><span class="nav-number">1.</span> <span class="nav-text">HEXO的开发分支与生产分支</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#开发分支-dev"><span class="nav-number">1.1.</span> <span class="nav-text">开发分支 dev</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生产分支-gh-pages"><span class="nav-number">1.2.</span> <span class="nav-text">生产分支 gh-pages</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Travis-CI"><span class="nav-number">2.</span> <span class="nav-text">Travis CI</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-编译并同步到gh-pages"><span class="nav-number">2.1.</span> <span class="nav-text">1. 编译并同步到gh-pages</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-CI到我的服务器"><span class="nav-number">2.2.</span> <span class="nav-text">2. CI到我的服务器</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  
  <span class="with-love" id="heart">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yszar</span>

  

  
</div>


  










<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共38.6k字</span>
</div>
<div class="post-count">
	<a href="http://www.miitbeian.gov.cn/" rel="external nofollow noopener noreferrer" target="_blank">陇ICP备15003024号</a>
</div>


<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，订阅本博客</div>
    </div>
  </div>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










   
     
       <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

      <script src="/js/src/md5.min.js"></script>

       <script type="text/javascript">
         const gitalk = new Gitalk({
           clientID: '54f26977793794b45255',
           clientSecret: '568cccb3bdde42eca6c05ab0680b4617bbb58c4f',
           repo: 'yszar.github.io',
           owner: 'yszar',
           admin: 'yszar'.split(','),
           id: md5(location.pathname),
           pagerDirection: 'first',
           // facebook-like distraction free mode
           distractionFreeMode: false
         })
         gitalk.render('gitalk-container')
       </script>
     
   
 
  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "iUS887d8BnkY3Gqc9FJX70fE-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "iUS887d8BnkY3Gqc9FJX70fE-gzGzoHsz",
                'X-LC-Key': "ekF4kKyQDgrDkIBadj3IDrVA",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  <script type="text/javascript">
  wpac_init = window.wpac_init || [];
  wpac_init.push({widget: 'Rating', id: 14244,
    el: 'wpac-rating',
    color: 'fc6423'
  });
  (function() {
    if ('WIDGETPACK_LOADED' in window) return;
    WIDGETPACK_LOADED = true;
    var mc = document.createElement('script');
    mc.type = 'text/javascript';
    mc.async = true;
    mc.src = '//embed.widgetpack.com/widget.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
  })();
  </script>


  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('复制成功')
          else $(this).text('复制失败')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('复制')
        }, 300)
      }).append(e)
    })
  </script>


  
</body>
</html>
